package net;

import game.Client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import util.ConfPropertiesUtil;
import util.LogUtil;

/**
 * netty服务
 */
public class NettyProtobufClient {

    EventLoopGroup eventLoopGroup;

    public NettyProtobufClient() {

    }

    public void init(Client client) {
        //启动监听
        eventLoopGroup = new NioEventLoopGroup();

        Bootstrap clientBotstrap = new Bootstrap();
        clientBotstrap.group(eventLoopGroup);
        clientBotstrap.channel(NioSocketChannel.class);
        clientBotstrap.option(ChannelOption.TCP_NODELAY, true);
        clientBotstrap.handler(new NettyProtobufClientInitializer(client));

        //绑定端口
        clientBotstrap.connect(ConfPropertiesUtil.getInstance()._IP, ConfPropertiesUtil.getInstance()._PORT);
        LogUtil.game.debug("客户端尝试连接服务器");
    }

    public void close() {
        if (null != eventLoopGroup) {
            eventLoopGroup.shutdownGracefully();
        }
        LogUtil.game.debug("客户端断开服务器链接");
    }
}
